package com.jee.ssm.modules.hikDevice.controller;

import cn.hutool.http.HttpRequest;
import cn.hutool.setting.dialect.Props;
import com.alibaba.fastjson.JSONObject;
import com.jee.ssm.common.utils.PropertiesLoader;
import com.jee.ssm.model.*;
import com.jee.ssm.modules.hikDevice.services.HikDeviceService;
import com.jee.ssm.common.log.AdminControllerLog;
import com.jee.ssm.modules.hikDeviceBerth.services.HikDeviceBerthService;
import com.jee.ssm.modules.ssm.controller.AdminBaseController;
import com.jee.ssm.model.json.Tip;
import com.jee.ssm.model.param.ParamMap;
import com.jee.ssm.common.utils.UUIDFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* 海康设备管理 Controller
* @author GaoXiang
* @version 1.0
*/
@Controller
@RequestMapping("/hikDevice")
public class HikDeviceController extends AdminBaseController<HikDevice> {


    /**
     * @Description 获取全部路侧停车场
     * @author yanzengbao
     * @date 2020/7/20 上午9:15
     */
    public void getLuceParkList(ModelMap model){
        try {
            Props props = new Props("config/project.properties");
            String serverUrl = props.getProperty("server.url");
            String method = props.getStr("getRoadsideParking");
            String result = HttpRequest.get(serverUrl + method).execute().body();
            List<Park> parkList = JSONObject.parseArray(result,Park.class);
            model.put("parkList",parkList);
        }catch (Exception e){
            //e.printStackTrace();
            System.out.println("服务器未链接！");
        }
    }


    /**
     * 进入海康设备添加页面 携带一个生成的id --> longId
     * @param model 返回的实体容器
     * @return 添加页面
     */
    @RequestMapping(value="/add")
    @RequiresPermissions("hikDevice:add")
    public String add(ModelMap model){
        //获取服务器全部路侧停车场
        getLuceParkList(model);

        model.put("longId", UUIDFactory.getStringId());
        return "manager/hikDevice/add";
    }


    /**
     * 进入海康设备编辑页面
     * @param model 返回海康设备的容器
     * @param id 海康设备id
     * @return 编辑页面
     */
    @RequestMapping(value="/edit")
    @RequiresPermissions("hikDevice:edit")
    public String edit(ModelMap model, @RequestParam String id) {

        model.put("data",hikDeviceService.selectById(id));
        return "manager/hikDevice/edit";
    }


    /**
     * 海康设备添加
     * @param hikDevice 带id的海康设备对象
     * @return 成功状态
     */
    @RequestMapping(value="/save")
    @ResponseBody
    @RequiresPermissions("hikDevice:add")
    @AdminControllerLog(description = "添加海康设备" )
    public Tip save(HikDevice hikDevice) {

        try {
            //判断设备编号是否存在
            HikDevice hd = hikDeviceService.selectByNumber(hikDevice.getHikNumber());
            if(hd != null) return new Tip(1,"设备编号已存在，请检查后重新输入！");

            hikDevice.setCreateTime(new Date());
            hikDeviceService.insert(hikDevice);
            return new Tip();
        } catch (Exception e) {
            //e.printStackTrace();
            return new Tip(1,"添加失败！");
        }

    }


    /**
     * 根据 id 修改海康设备
     * @param hikDevice 带id的海康设备对象
     * @return 成功状态
     */
    @RequestMapping(value="/update")
    @ResponseBody
    @RequiresPermissions("hikDevice:edit")
    @AdminControllerLog(description = "修改海康设备" )
    public Tip update(HikDevice hikDevice) {

        try {

            HikDevice hikDevice1 = hikDeviceService.selectByNumber(hikDevice.getHikNumber());
            if(hikDevice1 != null){
                if(!hikDevice1.getId().equals(hikDevice.getId())) return new Tip(1,"此设备已存在，请重新输入！");
            }
            //修改关联表的数据
            HikDeviceBerth hikDeviceBerth = new HikDeviceBerth(hikDevice.getId(),hikDevice.getHikNumber(),hikDevice.getHikName());
            hikDeviceBerthService.updateByHikId(hikDeviceBerth);
            hikDeviceService.updateById(hikDevice);
            return new Tip();
        } catch (Exception e) {
            //e.printStackTrace();
            return new Tip(1,"修改失败！");
        }

    }


    /**
     * 根据 id 删除海康设备 并关联删除设备-车位绑定的关联信息
     * @param id 海康设备id
     * @return 成功状态
     */
    @RequestMapping(value="/delete")
    @ResponseBody
    @RequiresPermissions("hikDevice:delete")
    @AdminControllerLog(description = "删除海康设备" )
    public Tip delete(@RequestParam String id) {

        try {
            //删除关联信息
            hikDeviceBerthService.deleteByHikId(id);
            hikDeviceService.deleteById(id);
            return new Tip();
        } catch (Exception e) {
            //e.printStackTrace();
            return new Tip(1,"删除失败！");
        }

    }


    /**
     * 根据 id 列表批量删除
     * @param ids 海康设备id List
     * @return 成功状态
     */
    @RequestMapping(value="/deleteByIds")
    @ResponseBody
    @RequiresPermissions("hikDevice:delete")
    @AdminControllerLog(description = "批量删除海康设备" )
    public Tip deleteByIds(@RequestParam("ids") List<String> ids) {

        try {
            hikDeviceService.deleteByIds(ids);
            return new Tip();
        } catch (Exception e) {
            //e.printStackTrace();
            return new Tip(1,"批量删除失败！");
        }

    }


    /**
     * 根据 id 查找海康设备
     * @param id 海康设备id
     * @return 海康设备对象 json
     */
    @RequestMapping(value="/findJson")
    @ResponseBody
    @RequiresPermissions("hikDevice:list")
    public HikDevice find(@RequestParam String id) {

        return hikDeviceService.selectById(id);
    }


    /**
     * 获取海康设备列表 获取全部 不分页
     * @param request 请求参数
     * @return 海康设备列表页面
     */
    @RequestMapping(value="/all")
    @RequiresPermissions("hikDevice:list")
    public String all(HttpServletRequest request,ModelMap modelMap) {

        return list(request,modelMap,1,0);
    }


    /**
     * 获取海康设备列表 分页
     * @param request 请求参数
     * @param page 第几页
     * @param size 每页大小
     * @return 海康设备列表页面
     */
    @RequestMapping(value="/list")
    @RequiresPermissions("hikDevice:list")
    public String list(HttpServletRequest request,ModelMap modelMap,Integer page,Integer size) {

        modelMap.put("pageInfo",hikDeviceService.list(new ParamMap(request),page,size));
        modelMap.putAll(new ParamMap(request));
        return "manager/hikDevice/list";
    }


    /**
     * 描述： 海康设备绑定车位
     * 创建时间：2020/7/21  YanZengBao
     * 修改时间：2020/7/21  YanZengBao 加注释
     * 修改时间：
     */
    @RequestMapping("/manageBerth")
    public  String manageBerth(String id,ModelMap modelMap){
        HikDevice hikDevice= hikDeviceService.selectById(id);
        if(hikDevice !=null){
            String parkId = hikDevice.getParkId();
            PropertiesLoader propertiesLoader = new PropertiesLoader("config/project.properties");
            String serverUrl = propertiesLoader.getProperty("server.url");
            String method = propertiesLoader.getProperty("getAllBerthByParkId");
            String result = HttpRequest.get(serverUrl + method).form("parkId",parkId).execute().body();
            List<Berth> berths = JSONObject.parseArray(result,Berth.class);
            for(Berth berth:berths){
                Map map = new HashMap<>();
                map.put("berthId",berth.getId());
                //map.put("hikId",id);
                List<HikDeviceBerth> hikDeviceBerths = hikDeviceBerthService.selectByParam(map);
                if(hikDeviceBerths != null && !hikDeviceBerths.isEmpty()){
                    for (HikDeviceBerth hdb:hikDeviceBerths) {
                        if(hdb.getHikId().equals(id)){
                            berth.setSelected(true);
                        }
                    }
                }
            }
            modelMap.put("berths",berths);
            modelMap.put("parkName",hikDevice.getParkName());
        }
        return  "/manager/hikDevice/manage_berth";
    }


    //---------------------------- property -------------------------------

    @Resource
    private HikDeviceService hikDeviceService;
    @Resource
    private HikDeviceBerthService hikDeviceBerthService;

}
